package com.ztl.ztlcantest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;

import com.ztl.jni.ZtlCanCallback;
import com.ztl.jni.ZtlCanManager;
import com.ztl.layout.GridSpacingItemDecoration;
import com.ztl.layout.MyAdapter;

import java.util.ArrayList;
import java.util.List;

import java.util.Arrays;


import android.text.Editable;
import android.text.TextWatcher;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private MyAdapter adapter;
    private List<List<String>> dataList;
    private EditText hexInput;
    private EditText baudRateInput;
    private EditText canidInput;
    private Spinner deviceNameSpinner;
    private Button openButton;
    private Button closeButton;
    private Button clearButton;
    CheckBox checkBoxEff;
    CheckBox checkBoxRtr;
    private boolean isOpened = false;
    private int mLastBaudrate = 0;
    static final int EXIT_FLAG_NONE         = 0;
    static final int EXIT_FLAG_BACKGROUND   = 1;
    static final int EXIT_FLAG_EXIT         = 2;
    private int mExitFlag = EXIT_FLAG_NONE;

    ZtlCanManager mZtlCanManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init_ui();
        ztl_init_can();
    }
    
    // ui 将接受的数据更新到ui上面
    Handler mHandler =  new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
//                tvInfo.setText(msg.obj.toString());
                String data1 = msg.getData().getString("data1");
                String data2 = msg.getData().getString("data2");
                String data3 = msg.getData().getString("data3");
                addNewRow( data1, data2, data3);
                return;
            }

        }
    };

    // 重要接口1 初始化
    int ztl_init_can(){
        // step 0, 重要接口，接受数据
        // step 0, use call back to recvive data
        ZtlCanCallback mZtlCanCallback = new ZtlCanCallback() {

            // 数据是byte[]
            @Override
            public void get_recv_can_data(boolean eff, boolean rtr, String canId,
                                          byte[] canData, int dataLen) {
                // 打印接受的 数据
                System.out.println("get_recv_can_data len:"+dataLen+"  eff:"+eff + " rtr:"+rtr + " canId:"+canId+ "#"+ZtlCanManager.bytesToHex (canData,null).toUpperCase());
                // 将数据发送到handler 去显示到ui， 如果你没有相关的ui 不用下面的代码
                String data1 = "+"+(eff?"Ext":"Std")+";"+(rtr?"R":"");
                Message message = mHandler.obtainMessage();
                message.what = 1;
                Bundle bundle = new Bundle();
                bundle.putString("data1",data1);
                bundle.putString("data2",canId);  //往Bundle中存放数据
                bundle.putString("data3",ZtlCanManager.bytesToHex (canData," ").toUpperCase());  //往Bundle中put数据
                message.setData(bundle);//mes利用Bundle传递数据
                mHandler.sendMessage(message);
//                addNewRow("-",canId, ZtlCanManager.bytesToHex (canData," ").toUpperCase());
            }
        };

        mZtlCanManager = new ZtlCanManager(mZtlCanCallback);
        mZtlCanManager.mDebug = false;

        ////////////////////////////////////////////////////////////////
        // 你可以不用初始化ui，直接使用下面的示例。
        // you can just use it without init_ui()
        ////// step 1 设置波特率，打开can口
        //        ztl_init_can_and_baudrate("can0", 250000);
        //        mLastBaudrate = 250000;
        //        ztl_init_can_open("can0");

        ////////////////////////////////////////////////////////////////
        // //////step 2 send data 发送数据
        // //////step 2.1 send string demo : cansend can0 789#123456 ； 传递字符串例子
                //        String strdata = "123456";
                //        int ret = mZtlCanManager.sendCan(0x789, 0x0, 0x0, strdata);
                //        System.out.println("send can data ret:" + ret);
        ////////////////////////////////////////////////////////////////
        // ///////step 2.2 send byte buffer demo: cansend can0 123#010203 ； 传递byte buffer例子
                //        byte[] data = {0x01,0x02,0x03};
                //        int ret2 = mZtlCanManager.sendCan(  0x123, 0, 0, data.length,  data);
                //        System.out.println("send can data ret:" + ret2);
        ////////////////////////////////////////////////////////////////
        // //////step 2.3 send byte buffer demo: cansend can0 123456#010203 ；拓展帧例子
                //        ret2 = mZtlCanManager.sendCan(  0x123456, 1, 0, data.length,  data);
                //        System.out.println("send can data ret:" + ret2);
        ////////////////////////////////////////////////////////////////
        //////step 2.4 send byte buffer demo: cansend can0 123456#R010203 ；远程帧例子
        //        ret2 = mZtlCanManager.sendCan(  0x123456, 0, 1, data.length,  data);
        //        System.out.println("send can data ret:" + ret2);

        // exit close can
        // // ztl_close_can();
        return 0;
    }

    // 重要接口2 初始化波特率
    int ztl_init_can_and_baudrate(String strCanName , int baudrate ){
        return mZtlCanManager.init(strCanName, baudrate);
    }

    // 重要接口3 打开can
    int ztl_init_can_open(String strCanName){
        if(mZtlCanManager.openCan(strCanName)>=0){
            mZtlCanManager.startCanReceiverThread();
            return 0;
        }else{
            System.out.println("open can failed");
            return -1;
        }
    }

    // 重要接口4 关闭can，这个接口可能会耗时10ms
    void ztl_close_can(){
        mZtlCanManager.closeCan();
    }

    void init_ui(){
        dataList = new ArrayList<>();
        dataList.add(Arrays.asList(getString(R.string.data_id), getString(R.string.can_id), getString(R.string.data_hex)));

        recyclerView = findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.grid_spacing);//间距
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, spacingInPixels, true));//间距

        adapter = new MyAdapter(dataList);
        recyclerView.setAdapter(adapter);

        hexInput = findViewById(R.id.hex_input);
        baudRateInput = findViewById(R.id.baud_rate_input);
        deviceNameSpinner = findViewById(R.id.device_name_spinner);
        openButton = findViewById(R.id.open_button);
        closeButton = findViewById(R.id.close_button);
        clearButton = findViewById(R.id.clear_button);
        checkBoxEff = findViewById(R.id.checkBoxEff);
        checkBoxRtr = findViewById(R.id.checkBoxRtr);
        canidInput  = findViewById(R.id.canid_input);
        Button sendButton = findViewById(R.id.send_button);
        
        // 监听输入的数据是否是16进制
        hexInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String input = s.toString();
                String[] parts = input.split(" ");
                for (String part : parts) {
                    if (!part.matches("[0-9A-Fa-f]+")) {
                        hexInput.setError("Only hex values are allowed, separated by spaces");
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 打开can
        openButton.setOnClickListener(v -> {
            String baudRate = baudRateInput.getText().toString().trim();
            if (baudRate.isEmpty()) {
                Toast.makeText(this, getString(R.string.baud_rate_empty_error), Toast.LENGTH_SHORT).show();
            } else if (!isOpened) {
                int ibaudRate = Integer.valueOf(baudRate);
                String deviceName = deviceNameSpinner.getSelectedItem().toString();

                if(mLastBaudrate!=ibaudRate){
                    ztl_init_can_and_baudrate(deviceName , ibaudRate);
                    mLastBaudrate = ibaudRate;
                }
                if(ztl_init_can_open(  deviceName) >= 0){
                    Toast.makeText(this, getString(R.string.open_clicked_message, baudRate, deviceName), Toast.LENGTH_SHORT).show();
                    baudRateInput.setEnabled(false);
                    deviceNameSpinner.setEnabled(false);
                    sendButton.setEnabled(true);
                    openButton.setEnabled(false);
                    closeButton.setEnabled(true);
                    isOpened = true;
                }else{
                    Toast.makeText(this, getString(R.string.open_clicked_message, baudRate, deviceName)+" error", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 关闭can
        closeButton.setOnClickListener(v -> {
            if (isOpened) {
                ztl_close_can();
                Toast.makeText(this, getString(R.string.close_clicked_message), Toast.LENGTH_SHORT).show();
                baudRateInput.setEnabled(true);
                deviceNameSpinner.setEnabled(true);
                sendButton.setEnabled(false);
                openButton.setEnabled(true);
                closeButton.setEnabled(false);
                isOpened = false;
            }
        });

        // 发送按钮
        sendButton.setOnClickListener(v -> {
            String hexData = hexInput.getText().toString().trim();
            if (hexData.matches("([0-9A-Fa-f]+\\s?)+")) {

                boolean eff = checkBoxEff.isChecked();
                boolean rtr = checkBoxRtr.isChecked();

                String canId = canidInput.getText().toString();
                long lcanId = 0;
                try {
                    lcanId = Long.valueOf(canId, 16).longValue();;
                }catch (Exception e){
                    e.printStackTrace();
                    return ;
                }
                // step 2.1 send string demo : cansend can0 789#123456
                int ret = mZtlCanManager.sendCan(lcanId, eff?1:0, rtr?1:0, hexData.replace(" ",""));
                // step 2.2 send byte buffer demo: cansend can0 123#010203
                //        byte[] data = {0x01,0x02,0x03};
                //        int ret2 = mZtlCanManager.sendCan(  0x123, 0, 0, data.length,  data);
                //        System.out.println("send can data ret:" + ret2);
                String data1 = "-"+(eff?"Ext":"Std")+";"+(rtr?"R":"");
                System.out.println("send data :"+canId+"#"+hexData);
                addNewRow(data1,canId ,hexData);
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

                if (getCurrentFocus() != null && null != imm) {
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); // 关闭键盘
                }
            } else {
                Toast.makeText(this, getString(R.string.invalid_hex_data), Toast.LENGTH_SHORT).show();
            }
        });
        sendButton.setEnabled(false);

        clearButton.setOnClickListener(v -> {
            dataList.clear();
            dataList.add(Arrays.asList(getString(R.string.data_id), getString(R.string.can_id), getString(R.string.data_hex)));
            adapter.notifyDataSetChanged();
        });
    }

    /***************************************
     * 显示数据到列表里面
     * @param data1
     * @param data2
     * @param hexData
     */
    private void addNewRow(String data1,String data2, String hexData) {
//        String[] parts = hexData.split(" ");
        if(recyclerView==null)return ;
        List<String> newRow = new ArrayList<>();
        newRow.add(dataList.size()+" "+data1);
        newRow.add(data2);
        newRow.add(hexData);

        dataList.add(newRow);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(dataList.size() - 1);
    }

    void checkExit(){
        AlertDialog alertDialog=new AlertDialog.Builder(this)
                .setTitle("确认操作")
                .setNegativeButton("后台", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //执行代码
//                        alertDialog.dismiss();//销毁对话框
                        mExitFlag = EXIT_FLAG_BACKGROUND;
                        onBackPressed();
                    }

                })
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //执行代码
                        mExitFlag = EXIT_FLAG_EXIT;
                        onBackPressed();
                    }
                })
                .create();

        alertDialog.show();

    }

    @Override
    public void onBackPressed() {
        switch (mExitFlag){
            case EXIT_FLAG_EXIT:
                super.onBackPressed();
                ztl_close_can();
                System.exit(0);
                return ;
            case EXIT_FLAG_BACKGROUND:
                super.onBackPressed();
                mExitFlag = EXIT_FLAG_NONE;
                return ;
        }
        checkExit();
        return ;


    }
}



